<?php

declare(strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Middleware\User;

use App\Constants\Constants;
use App\Exception\BusinessException;
use App\Kernel\Util\AgentJwtInstance;
use App\Kernel\Util\StoreJwtInstance;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * 代理商后台用户Token验证中间件
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Middleware
 */
class AgentMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 获取token
        $token = $request->getHeaderLine(Constants::AUTHORIZATION);

        // 未登录
        if ($token == '') {
            throw new BusinessException(401, __('api.COMMON.NO_LOGIN'));
        }

        try {
            AgentJwtInstance::instance()->decode($token);
        }
        catch (CustomException $e) {
            throw new BusinessException(401, __('api.COMMON.TOKEN_INVALID'));
        }

        // check user status
        $accessUser = AgentJwtInstance::instance()->build()->getAgent();

        if (!$accessUser || $accessUser->status !== 1) {
            throw new BusinessException(401, __('api.USER.STATUS_EXCEPTION'));
        }
        return $handler->handle($request);
    }
}